package com.xyy.saas.payment.adpater.channel.setting;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.UnionPayConfigVo;
import com.xyy.saas.payment.dao.model.AlipaySettings;
import com.xyy.saas.payment.dao.model.UnionPaySettings;
import com.xyy.saas.payment.dao.model.WxSettings;
import com.xyy.saas.payment.service.ChannelSettingsService;
import com.xyy.saas.payment.util.Base64;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangtianqi
 * @date 2020/11/26 11:04
 */
@Slf4j
@Component
public class ChannelSettingManager {

    private static final String ALIPAY_SERVER_URL = "https://openapi.alipay.com/gateway.do";

    @Autowired
    private ChannelSettingsService channelSettingsService;

    /**
     * 武汉小药药转北京药帮忙主体
     */
    public WxSettings getWXSettings(String receiveId, String businessOrderType, String payMode) {
        String oldBusinessOrderType = businessOrderType;
        log.info("微信settle.transtoxyy.merchants 转换请求参数 {} {} {} ", receiveId, businessOrderType, payMode);
        // 如果businessOrderType不以pingan结尾 且 businessOrderType为ec_*
        if (!businessOrderType.endsWith(Constants.CHANNEL_PINGAN_NAME) && null != businessOrderType && businessOrderType.toLowerCase().startsWith("ec_")) {
            businessOrderType = businessOrderType + "_" + Constants.CHANNEL_PINGAN_NAME;
            log.info("微信settle.transtoxyy.merchants 转换为_pingan {} {} {} {}", receiveId, oldBusinessOrderType, businessOrderType, payMode);
        }
        WxSettings wxSettings = channelSettingsService.queryWXByBusinessOrderTypeAndPayMode(businessOrderType, payMode);
        if (null == wxSettings) {
            log.info("微信settle.transtoxyy.merchants 未查询到配置，查询原数据 {} {} {} ", oldBusinessOrderType, businessOrderType, payMode);
            wxSettings = channelSettingsService.queryWXByBusinessOrderTypeAndPayMode(oldBusinessOrderType, payMode);
        }
        return wxSettings;
    }

    /**
     * 武汉小药药转北京药帮忙主体
     */
    public AlipaySettings getAlipaySettings(String receiveId, String businessOrderType, String payMode) {
        String oldBusinessOrderType = businessOrderType;
        log.info("支付宝settle.transtoxyy.merchants 转换请求参数 {} {} {} ", receiveId, businessOrderType, payMode);
        // 如果businessOrderType不以pingan结尾 且 businessOrderType为ec_*
        if (!businessOrderType.endsWith(Constants.CHANNEL_PINGAN_NAME) && null != businessOrderType && businessOrderType.toLowerCase().startsWith("ec_")) {
            businessOrderType = businessOrderType + "_" + Constants.CHANNEL_PINGAN_NAME;
            log.info("支付宝settle.transtoxyy.merchants 转换为_pingan {} {} {} {}", receiveId, oldBusinessOrderType, businessOrderType, payMode);
        }
        AlipaySettings alipaySettings = channelSettingsService.queryAlipayByBusinessOrderTypeAndPayMode(businessOrderType, payMode);
        if (null == alipaySettings) {
            log.info("支付宝settle.transtoxyy.merchants 未查询到配置，查询原数据 {} {} {} ", oldBusinessOrderType, businessOrderType, payMode);
            alipaySettings = channelSettingsService.queryAlipayByBusinessOrderTypeAndPayMode(oldBusinessOrderType, payMode);
        }
        return alipaySettings;
    }

    public AlipaySettings getAlipaySettingsByAliAppId(String appId) {
        AlipaySettings alipaySettings = new AlipaySettings();
        alipaySettings.setAlipayAppId(appId);
        List<AlipaySettings> list = channelSettingsService.queryAlipayAll(alipaySettings);
        if(list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    public WxSettings getWXSettingsByAppIdAndMchId(String appId, String mchId) {
        WxSettings wxSettings = new WxSettings();
        wxSettings.setWxAppId(appId);
        wxSettings.setMerchantId(mchId);
        List<WxSettings> list = channelSettingsService.queryWXAll(wxSettings);
        if(list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    public WxSettings getWXSettingByMchId(String mchId) {
        return getWXSettingsByMchId(mchId).get(NumberUtils.INTEGER_ZERO);
    }

    public List<WxSettings> getWXSettingsByMchId(String mchId) {
        WxSettings wxSettings = new WxSettings();
        wxSettings.setMerchantId(mchId);
        return channelSettingsService.queryWXAll(wxSettings);
    }

    public AlipayClient getAlipayClient(String receiveId, String businessOrderType, String payMode) {
        AlipaySettings alipaySettings = getAlipaySettings(receiveId, businessOrderType, payMode);
        return new DefaultAlipayClient(ALIPAY_SERVER_URL, alipaySettings.getAlipayAppId(), alipaySettings.getAppPrivateKey(), "json", "UTF-8", alipaySettings.getAlipayPublicKey(), alipaySettings.getSignType());
    }

    public AlipayClient getAlipayClient(String appId) {
        AlipaySettings alipaySettings = getAlipaySettingsByAliAppId(appId);
        return new DefaultAlipayClient(ALIPAY_SERVER_URL, alipaySettings.getAlipayAppId(), alipaySettings.getAppPrivateKey(), "json", "UTF-8", alipaySettings.getAlipayPublicKey(), alipaySettings.getSignType());
    }

    @SneakyThrows
    public Map<String, String> getWXParam(String receiveId, String businessOrderType, String payMode){
        WxSettings settings = getWXSettings(receiveId, businessOrderType, payMode);
        Map<String, String> settingMap = new HashMap<>();

        if (settings == null) {
            throw new PaymentException(ResultCodeEnum.WXPAY_SETTING_NOT_EXITS);
        }

        settingMap.put("mch_id",settings.getMerchantId());
        settingMap.put("appid",settings.getWxAppId());
        settingMap.put("apiKey",settings.getApiSecret());
        return settingMap;
    }

    public UnionPaySettings getUnionPaySettings(String businessOrderType, String payMode) {
        return channelSettingsService.queryUnionPayByBusinessOrderTypeAndPayMode(businessOrderType, payMode);
    }

    public UnionPayConfigVo getUnionPayConfig(String businessOrderType, String payMode) {
        UnionPaySettings unionPaySettings = channelSettingsService.queryUnionPayByBusinessOrderTypeAndPayMode(businessOrderType, payMode);

        if(unionPaySettings == null){
            return null;
        }

        UnionPayConfigVo unionPayConfigVo = new UnionPayConfigVo();
        unionPayConfigVo.setAppId(new String(Base64.decode(unionPaySettings.getAppId())));
        unionPayConfigVo.setMachId(new String(Base64.decode(unionPaySettings.getMachId())));
        unionPayConfigVo.setUnionpayKey(new String(Base64.decode(unionPaySettings.getUnionpayKey())));
        unionPayConfigVo.setPid(new String(Base64.decode(unionPaySettings.getPid())));

        return unionPayConfigVo;
    }
}
